import User, { type IView } from '../../../selector/user';
import { userTypePrefix, type Option } from '../../../../../types';
import ApprovalService from '../base/service';

class UserService extends ApprovalService<Option> implements IView {
  prefix = userTypePrefix.user;

  options: Option[] = [];
  component = User;
  value: Option[] = [];

  // user 单个的时候使用assignee属性

  updateProperties(value: Option[]) {
    if (value.length <= 1) {
      const element = this.panel.getElement();
      this.root.getModeling().updateProperties(
        element,
        {
          'flowable:assignee': value[0]?.value || '',
          // 清空候选组
          'flowable:candidateGroups': undefined,
          'flowable:text': value[0]?.label || ''
        },
      );
    } else {
      super.updateProperties(value);
    }
  }

  init() {
    const element = this.panel.getElement();
    const ids = element.businessObject.candidateGroups as string || '';
    if (ids) {
      super.init();
    } else {
      const id = element.businessObject.assignee as string || '';
      if (id) {
        const label = element.businessObject.$attrs['flowable:text'] as string || '';
        this.value = [{ label, value: id }];
      } else {
        this.value = [];
      }
    }
  }

  initData(value: Option[] = []): void {
    this.value = value;
    this.updateProperties(value);
  }
}

export default UserService;
